package com.study.security.web.intercepter;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyIntercepter implements HandlerInterceptor {

    /**
     * controller方法调用之前调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
//        System.out.println("preHandle....");

//        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
//        System.out.println((((HandlerMethod) handler).getMethod().getName()));
        httpServletRequest.setAttribute("start",System.currentTimeMillis());
        return true;
    }

    /**
     * controller方法调用之后调用，如果异常，则不会执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle....");
        long start = (long) httpServletRequest.getAttribute("start");
//        System.out.println("time intercepter 耗时："+(System.currentTimeMillis()-start));
    }

    /**
     * 不管controller方法是否有异常，都会执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
//        System.out.println("afterCompletion....");
        long start = (long) httpServletRequest.getAttribute("start");
//        System.out.println("time intercepter 耗时："+(System.currentTimeMillis()-start));
    }
}
